﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;


public class FileTools
{

    /// <summary>
    /// 密匙- （密匙长度必选为32位）
    /// </summary>
    private const string Encrypt_Key = "company_project_myAppName_key_32";

    private const string Encrypt_IV = "abcdefghijklmnop";

    /// <summary>
    /// 获取文件MD5
    /// </summary>
    /// <param name="filePath"></param>
    /// <returns></returns>
    static public string GetFileMd5(string filePath)
    {
        StringBuilder _sb = new StringBuilder();
        FileStream _fs = new FileStream(filePath, FileMode.Open);
        MD5 _md5 = new MD5CryptoServiceProvider();
        byte[] _buffer = _md5.ComputeHash(_fs);
        for (int i = 0; i < _buffer.Length; i++)
            _sb.Append(_buffer[i].ToString("x2"));
        _fs.Close();
        _fs.Dispose();
        return _sb.ToString();
    }



    /// <summary>
    /// 文本加密
    /// </summary>
    /// <param name="pContent">需要加密的内容</param>
    /// <returns></returns>
   static public string EncryptToString(string pContent)
    {
        byte[] _contentBytes = Encoding.UTF8.GetBytes(pContent);
        byte[] _keyBytes = Encoding.UTF8.GetBytes(Encrypt_Key);
        RijndaelManaged _rijndael = new RijndaelManaged();
        _rijndael.Key = _keyBytes;
        _rijndael.Mode = CipherMode.ECB;
        _rijndael.Padding = PaddingMode.PKCS7;
        _rijndael.IV = Encoding.UTF8.GetBytes(Encrypt_IV);
        ICryptoTransform _transform = _rijndael.CreateEncryptor();
        byte[] _cipherBytes = _transform.TransformFinalBlock(_contentBytes, 0, _contentBytes.Length);
        return Convert.ToBase64String(_cipherBytes);
    }

    /// <summary>
    /// 文本解密
    /// </summary>
    /// <param name="pContent">需要解密的内容</param>
    /// <returns></returns>
    static public string DecryptToString(string pContent)
    {
        byte[] _contentBytes = Convert.FromBase64String(pContent);
        byte[] _keyBytes = Encoding.UTF8.GetBytes(Encrypt_Key);
        RijndaelManaged _rijndael = new RijndaelManaged();
        _rijndael.Key = _keyBytes;
        _rijndael.Mode = CipherMode.ECB;
        _rijndael.Padding = PaddingMode.PKCS7;
        _rijndael.IV = Encoding.UTF8.GetBytes(Encrypt_IV);
        ICryptoTransform _transform = _rijndael.CreateDecryptor();
        byte[] _cipherBytes = _transform.TransformFinalBlock(_contentBytes, 0, _contentBytes.Length);
        return Encoding.UTF8.GetString(_cipherBytes);
    }

    public static MemoryStream StreamToMemory(Stream ins)
    {
        MemoryStream ms = new MemoryStream();
        if (ins == null && !ins.CanRead)
        {
            return ms;
        }

        byte[] bin = new byte[1024];
        int len;

        do
        {
            len = ins.Read(bin, 0, 1024);
            ms.Write(bin, 0, len);
        }
        while (len > 0);

        return ms;
    }

}
